<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  -->
    <el-card>
      <el-alert :closable="false" show-icon title="注意：只允许为第三季分类设置相关参数！" type="warning"></el-alert>
      <!--  -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            expand-trigger="hover"
            :options="catelist"
            :props="cateProps"
            v-model="selectedKeys"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="paramsDialogVisible = true"
            type="primary"
            :disabled="isBtndisabled"
          >添加参数</el-button>
          <!--  -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="handleClose(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            @click="paramsDialogVisible = true"
            type="primary"
            :disabled="isBtndisabled"
          >添加属性</el-button>
          <!--  -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="handleClose(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      @close="paramsDialogClosed"
      :title="'添加'+titleText"
      :visible.sync="paramsDialogVisible"
      width="50%"
    >
      <el-form ref="paramsFormRef" label-width="100px" :model="addForm" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paramsDialogVisible=false">取 消</el-button>
        <el-button @click="addParams" type="primary">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      @close="editDialogClosed"
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form ref="editFormRef" label-width="100px" :model="editForm" :rules="editFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible=false">取 消</el-button>
        <el-button @click="editParams" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      catelist: [],
      // 级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        children: 'children',
        label: 'cat_name'
      },
      // 级联选择矿的双向绑定到的数组
      selectedKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      paramsDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    isBtndisabled() {
      if (this.selectedKeys.length !== 3) return true
      return false
    },
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    //动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
      handleClose(i,row){
          row.attr_vals.splice(i,1)
          this.saveAttrVals(row)
      },
      // 将对attr_vals的操作 保存到数据库中
      async saveAttrVals(row){
          if(row.inputValue.trim().length==0){
            row.inputValue = '';
            row.inputVisible = false;
            return 
        }
        //如果没有return则证明输入的内容，需要做后续处理
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = '';
        row.inputVisible = false;
        // 发请求
        const {data:res} = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
        })
        if(res.meta.status!==200) return this.$message.error('添加标签失败')
        this.$message({
            message: res.meta.msg,
            type: 'success'
        });
      },
    async handleInputConfirm(row) {
        if(row.inputValue.trim().length==0){
            row.inputValue = '';
            row.inputVisible = false;
            return 
        }
        //如果没有return则证明输入的内容，需要做后续处理
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = '';
        row.inputVisible = false;
        // 发请求
        const {data:res} = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
        })
        if(res.meta.status!==200) return this.$message.error('添加标签失败')
        this.$message({
            message: res.meta.msg,
            type: 'success'
        });
    },
    showInput(row) {
      row.inputVisible = true
      // 获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async getCateList() {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类失败！')
      this.catelist = res.data
      // console.log(this.catelist)
    },
    handleChange() {
      this.getParamsData()
    },
    handleTabClick() {
      //console.log(this.activeName);
      this.getParamsData()
    },
    async getParamsData() {
      // 不等于三 就不是三级分类
      if (this.selectedKeys.length !== 3) {
          this.selectedKeys = [];
          this.manyTableData = [];
          this.onlyTableData = [];
        return 
      }
      // console.log(this.selectedKeys)
      // 根据所选的id获取对应的参数
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示隐藏
        item.inputVisible = false
        // 文本输入框输入的值
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    paramsDialogClosed() {
      this.$refs.paramsFormRef.resetFields()
    },
    addParams() {
      this.$refs.paramsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.paramsDialogVisible = false
      })
    },
    async showEditDialog(id) {
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200)
        return this.$message.error('获取修改信息失败')
      this.editForm = res.data

      this.editDialogVisible = true
    },
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.editForm.attr_sel
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 根据id 删除对应的参数项
    async removeParams(attr_id) {
      const confirmRest = await this.$confirm(
        '次操作将永久删除该参数，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRest != 'confirm') {
        //取消
        return this.$message({
          message: '已经取消删除操作',
          type: 'info'
        })
      }
      // 发请求删除
      const { data: res } = await this.$axios.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除操作失败')
      this.$message({
        message: res.meta.msg,
        type: 'success'
      })
      this.getParamsData()
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.el-tag {
  margin: 0 8px;
}
.input-new-tag {
  width: 100px;
}
</style>